package 题目集.归并;

import org.junit.Test;

import java.util.PriorityQueue;

/**
 * 基数排序思想 {@link 题目集.hash.基数排序.demo02_合并K个升序链表}
 * https://leetcode.cn/problems/merge-k-sorted-lists/description/
 */
public class demo01_合并K个升序链表 {

    ListNode[] arr;

    public ListNode mergeKLists(ListNode[] lists) {
        if (lists.length == 0) return null;
        this.arr = lists;
        merge(0, lists.length - 1);
        return lists[0];
    }

    public void merge(int l, int r) {
        if (l == r) return;
        int m = l + r >> 1;
        merge(l, m);
        merge(m + 1, r);
        mergeTail(l, m + 1);
    }

    private void mergeTail(int h1, int h2) {
        ListNode p = arr[h1], q = arr[h2];
        /*哨兵节点*/
        ListNode head = new ListNode();
        ListNode pre = head;
        while (p != null && q != null) {
            if (p.val <= q.val) {
                pre.next = p;
                p = p.next;
            } else {
                pre.next = q;
                q = q.next;
            }
            pre = pre.next;
        }
        while (p != null) {
            pre.next = p;
            pre = pre.next;
            p = p.next;
        }
        while (q != null) {
            pre.next = q;
            pre = pre.next;
            q = q.next;
        }
        arr[h1] = head.next;
    }


    @Test
    public void test() {
        ListNode[] arr = new ListNode[3];
        arr[0] = new ListNode(1);
        arr[0].next = new ListNode(4);
        arr[0].next.next = new ListNode(5);

        arr[1] = new ListNode(1);
        arr[1].next = new ListNode(3);
        arr[1].next.next = new ListNode(4);

        arr[2] = new ListNode(2);
        arr[2].next = new ListNode(6);

        ListNode listNode = mergeKLists(arr);
        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }


    public int minOperations(int[] nums, int k) {
        PriorityQueue<Long> queue = new PriorityQueue<>();
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] < k) {
                queue.add((long) nums[i]);
            }
        }
        int res = 0;
        while (queue.size() >= 2) {
            long x = queue.poll();
            long y = queue.poll();
            long temp = Math.min(x, y) * 2 + Math.max(x, y);
            if (temp < k) {
                queue.add(temp);
            }
            res++;
        }
        if (queue.size() != 0) {
            res++;
        }
        return res;
    }

    @Test
    public void test2() {
        System.out.println(minOperations(new int[]{999999999, 999999999, 999999999}, 1000000000));
    }
}
